<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Order_center extends CI_Controller
{
	public $userInfo;
	public $siteGlobals;
	public function _load()
	{
		$this->load->model('User_model');
		$this->load->model('Order_model');
		$this->load->model('My_address_model');
		$this->load->model('Record_model');
		$this->load->library('user_verification');
		$this->load->library('finance_func');
		$this->load->model('Number_model');
	}
	function __construct()
	{
		parent::__construct();
		$this->_load();
		$is_login = $this->user_verification->is_login();
		if($is_login == 0)
		{
			redirect('sign/login', 'location', 303);
		}
		$userInfo = $this->User_model->getForId($this->input->cookie('user_id', TRUE));
		$this->userInfo = $userInfo[0];
		$this->siteGlobals = $this->common_func->siteGlobal();
	}
	function index()
	{
		$data['order_num'] = $this->Order_model->getOrderNum($this->userInfo);
		$page = $this->siteGlobals['page'];
		$page['now_page'] = ($this->uri->segment(4) == '')?'1':$this->uri->segment(4);
		$page['total_rows'] = $data['order_num']['total_rows']-$data['order_num']['ok_rows'];
		$data['page'] = ($page['total_rows'] <= $page['per_page'])?'':$this->common_func->getPage($page);

		$data['userInfo'] = $this->userInfo;
		$orderData = $this->Order_model->getOrder('all',$page['now_page'],$page['per_page'],$this->userInfo);
		$data['orderData'] = $orderData;
		$this->load->view('member/public/head',$data);
		$this->load->view('member/public/left');
		$this->load->view('member/order/index');
		$this->load->view('member/public/foot');
	}
	function finish()
	{
		$data['order_num'] = $this->Order_model->getOrderNum($this->userInfo);
		$page = $this->siteGlobals['page'];
		$page['now_page'] = ($this->uri->segment(4) == '')?'1':$this->uri->segment(4);
		$page['total_rows'] = $data['order_num']['ok_rows'];
		$data['page'] = ($page['total_rows'] <= $page['per_page'])?'':$this->common_func->getPage($page);

		$data['userInfo'] = $this->userInfo;
		$orderData = $this->Order_model->getOrder('2',$page['now_page'],$page['per_page'],$this->userInfo);
		$data['orderData'] = $orderData;
		$this->load->view('member/public/head',$data);
		$this->load->view('member/public/left');
		$this->load->view('member/order/finish');
		$this->load->view('member/public/foot');
	}
	function add()
	{
		$data['userInfo'] = $this->userInfo;
		$data['siteGlobals'] = $this->siteGlobals;
		$data['myAddressData'] = $this->My_address_model->getMyAddress($this->userInfo);
		$data['post_number'] = $this->Number_model->getNumberNum();
		$this->load->view('member/public/head',$data);
		$this->load->view('member/public/left');
		$this->load->view('member/order/add');
		$this->load->view('member/public/foot');
	}
	function showNumberInfo()
	{
		$this->db->trans_begin();
		$numberInfo = $this->common_func->queryPostInfo($_POST['post_number']);
		$dom = '<table class="table table-bordered"><thead><tr><th width="120px">扫描时间</th><th>跟踪流程</th></tr></thead><tbody>';
		if($numberInfo['info'] == -1)
		{
			$numberInfo['info'] = '<tr><td colspan=2>没有查询到相关物流信息</td></tr>';
		}
		else
		{
			$numberInfo['info'] = array_reverse($numberInfo['info']);
			$num = 0;
			foreach ($numberInfo['info'] as $k=>$v)
			{
				$num++;
				$dom .= '<tr><td>'.$v['do_time'].'</td><td>'.$v['info'].'</td></tr>';
				if($num >= $_POST['line'])
				{
	//				break;
				}
			}
			$numberInfo['info'] = $dom.'</tbody></table>';
		}
		if ($this->db->trans_status() === FALSE)
		{
			echo json_encode(-1);
		}
		else
		{
			$this->db->trans_commit();
			echo json_encode($numberInfo);
		}
	}
	function closeOrder()
	{
		$data['userInfo'] = $this->userInfo;
		$this->db->trans_begin();
		$orderId = (isset($_GET['oid']) && !empty($_GET['oid']))?$_GET['oid']:0;
		$orderData = $this->Order_model->getOrderById($orderId);
		if(isset($orderData[0]['id']))
		{
			switch ($orderData[0]['shop_type'])
			{
				case 0:
					$this->Order_model->sendOrder($orderData[0]['id'],array('static'=>3));//空包订单直接关闭
					break;
				case 1:
					break;
				case 2://底单申请
					$orderForNumber = $this->Order_model->getOrderByNumber($orderData[0]['info'][0]['post_number']);
					foreach ($orderForNumber as $k=>$v)
					{
						if($v['order_id'] != $orderData[0]['order_id'])//找到底单申请对应订单
						{
							$orderStatic = $this->Order_model->getOrderField($v['order_id'],'static');//获取对应总订单状态
							switch ($orderStatic)
							{
								case 1://总订单状态已付款
									$this->Order_model->sendOrder($orderData[0]['id'],array('static'=>3));//底单申请关闭
									$this->common_func->queryPostInfo($orderData[0]['info'][0]['post_number']);//查询物流信息处理连锁状态
									break;
								case 2://总订单状态已完成
									$this->Order_model->sendOrder($orderData[0]['id'],array('static'=>3));//底单申请关闭
									$this->Order_model->sendOrder($v['id'],array('post_static'=>1));//订单状态设置为已完成
									break;
							}
						}
					}
					break;
			}
			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
				$data['pay_result'] = array(
										'tips_img'=>'img/alert.gif',
										'tips_text'=>'<span style="color: rgb(241, 132, 31);">错误提示：系统故障！！！.</span><span>很抱歉的通知您，系统当前故障，该操作被意外终止，请稍后再进行该操作...</span>',
						);
				$this->common_func->publicView($data);
			}
			else
			{
				$this->db->trans_commit();
				redirect(site_url('member/order_center'),'location', 303);
			}
		}
		else
		{
			$data['pay_result'] = array(
									'tips_img'=>'img/error.gif',
									'tips_text'=>'<span style="color: rgb(241, 132, 31);">错误提示：非法操作！！！.</span><span>抱歉！该操作被意外终止，请正确操作。</span>',
					);
			$this->common_func->publicView($data);
		}
	}
	function getBill()
	{
		$this->db->trans_begin();
		$order = $this->Order_model->getOrderForRid($_GET['rid']);
		$orderForNumber = $this->Order_model->getOrderByNumber($order['post_number']);
		if(count($orderForNumber) > 1)
		{
			foreach ($orderForNumber as $k=>$v)
			{
				if($v['order_id'] != $order['order_id'])
				{
					$this->db->where('order_id',$v['order_id']);
					$this->db->update('order',array('static'=>0));
//					$this->Order_model->sendOrder($v['id'],array('static'=>0));
					$order_id = $v['order_id'];
				}
			}
		}
		else 
		{
			$data['shop_type'] = 2;
			$data['prince'] = $this->siteGlobals['prince'][$data['shop_type']];
			$data['post_number'] = $orderInfo['post_number'];
			$order_id = $this->Order_model->addOrder($data,$this->userInfo);
			$this->Order_model->setOrder($_GET['rid'],array('post_static'=>2));
		}
		if ($this->db->trans_status() === FALSE)
		{
			$this->db->trans_rollback();
			$data['pay_result'] = array(
									'tips_img'=>'img/alert.gif',
									'tips_text'=>'<span style="color: rgb(241, 132, 31);">错误提示：系统故障！！！.</span><span>很抱歉的通知您，系统当前故障，该操作被意外终止，请稍后再进行该操作...</span>',
					);
			$this->common_func->publicView($data);
		}
		else
		{
			$this->db->trans_commit();
			redirect('member/order_center/pay?oid='.$order_id, 'location', 303);
		}
	}
	function doAdd()
	{
		$data['siteGlobals'] = $this->siteGlobals;
		$data['userInfo'] = $this->userInfo;
		$this->db->trans_begin();
		if(isset($_FILES['userfile']) && !empty($_FILES))
		{
			if($_FILES['userfile']['name'] == '')
			{
				$data['pay_result'] = array(
									'tips_img'=>'img/alert.gif',
									'tips_text'=>'<span style="color: rgb(241, 132, 31);">错误提示：非法操作！！！.</span><span>请重新选择表格上传，请核对信息。</span>',
					);
				$this->common_func->publicView($data);
			}
			else
			{
				$file_mime = strstr($_FILES['userfile']['name'], '.');
				if($file_mime == '.xls' || $file_mime == '.xlsx')
				{
					$tradecode = $this->common_func->createTradecode($_POST['tradecode']);
					if($tradecode != $data['userInfo']['tradecode'])
					{/*安全码出错*/
						$data['pay_result'] = array(
												'tips_img'=>'img/error.gif',
												'tips_text'=>'<span style="color: rgb(241, 132, 31);">订单导入失败：账户交易安全码输入错误</span><span>请<a href="'.site_url('member/order_center/add').'">返回</a>重新输入交易安全码，以保证账户安全。账户交易安全码忘记？<a hreff="'.site_url('member/member_center/profile').'">重新设置安全码>></a></span>',
						);
						$this->common_func->publicView($data);
					}
					else
					{
						$path = './upload/excel/order_excel_'.$this->userInfo['id'].$file_mime;
						move_uploaded_file($_FILES['userfile']['tmp_name'], $path);
						$filePath = 'upload/excel/order_excel_'.$this->userInfo['id'].$file_mime;
						$excelData = $this->common_func->readerExcel($filePath);
						$order_id = $this->Order_model->addOrder($excelData,$this->userInfo,'more');
//						redirect('member/order_center/pay?oid='.$order_id, 'location', 303);
					}
				}
				else
				{
					$data['pay_result'] = array(
									'tips_img'=>'img/alert.gif',
									'tips_text'=>'<span style="color: rgb(241, 132, 31);">系统错误：文件有误！！！.</span><span>选择正确的文件格式上传。</span>',
					);
					$this->common_func->publicView($data);
				}
			}
		}
		else
		{
			$order_id = $this->Order_model->addOrder($_POST,$this->userInfo);
		}
		if ($this->db->trans_status() === FALSE)
		{
			$this->db->trans_rollback();
			$data['pay_result'] = array(
									'tips_img'=>'img/alert.gif',
									'tips_text'=>'<span style="color: rgb(241, 132, 31);">错误提示：系统故障！！！.</span><span>很抱歉的通知您，系统当前故障，该操作被意外终止，请稍后再进行该操作...</span>',
					);
			$this->common_func->publicView($data);
		}
		else
		{
			$this->db->trans_commit();
			redirect('member/order_center/pay?oid='.$order_id, 'location', 303);
		}
	}
	function pay()
	{
		$data['siteGlobals'] = $this->siteGlobals;
		$data['userInfo'] = $this->userInfo;
		$order_id = $this->input->get('oid');
		if($order_id)
		{
			$this->db->trans_begin();
			$orderData = $this->Order_model->getOrderById($order_id);
			/*安全辨认*/
			if($orderData[0]['static'] > 0 || $orderData[0]['for_user'] != $this->userInfo['id'])
			{
				$data['pay_result'] = array(
										'tips_img'=>'img/alert.gif',
										'tips_text'=>'<span style="color: rgb(241, 132, 31);">系统错误：非法操作！！！.</span><span>输入或操作非法，请核对信息。</span>',
						);
				$this->common_func->publicView($data);
			}
			else
			{
				foreach ($orderData as $k=>$v)
				{
					$data['order_data'][$v['order_id']] = array(
											'shop_type' => $v['shop_type'],
								);
					switch ($v['shop_type'])
					{
						case 0:
							foreach ($v['info'] as $i=>$j)
							{
								if($j['my_address_type'] > 0)
								{
									$orderMyAddress = $this->My_address_model->getMyAddressById($j['my_address_type']);
								}
								else
								{
									$orderMyAddress[0]['address_info'] = $j['my_address'];
								}
								$data['order_data'][$v['order_id']]['info'][] = array(
											'id'=>$j['id'],
											'prince'=>$j['prince'],
											'order_info'=>'从'.$orderMyAddress[0]['address_info'].'到'.$j['post_address'].'的空包',
								);
							}
							break;
						case 1:
							foreach ($v['info'] as $i=>$j)
							{
								$data['order_data'][$v['order_id']]['info'][] = array(
											'id'=>$j['id'],
											'prince'=>$j['prince'],
											'order_info'=>'给账户'.$j['post_name'].'的转账',
								);
								$data['siteGlobals']['prince'][1] = $j['prince'];
							}
							break;
						case 2:
							foreach ($v['info'] as $i=>$j)
							{
								$data['order_data'][$v['order_id']]['info'][] = array(
											'id'=>$j['id'],
											'prince'=>$j['prince'],
											'order_info'=>'为运单号&lt;'.$j['post_number'].'&gt;申请底单',
								);
								$data['siteGlobals']['prince'][1] = $j['prince'];
							}
							break;
					}
				}
			}
			if ($this->db->trans_status() === FALSE)
			{
				$this->db->trans_rollback();
				$data['pay_result'] = array(
										'tips_img'=>'img/alert.gif',
										'tips_text'=>'<span style="color: rgb(241, 132, 31);">错误提示：系统故障！！！.</span><span>很抱歉的通知您，系统当前故障，该操作被意外终止，请稍后再进行该操作...</span>',
						);
				$this->common_func->publicView($data);
			}
			else
			{
				$this->db->trans_commit();
				$this->load->view('member/public/head',$data);
				$this->load->view('member/public/left');
				$this->load->view('member/public/pay');
				$this->load->view('member/public/foot');
			}
		}
		else
		{
			$data['pay_result'] = array(
										'tips_img'=>'img/alert.gif',
										'tips_text'=>'<span style="color: rgb(241, 132, 31);">系统错误：非法操作！！！.</span><span>输入或操作非法，请核对信息。</span>',
						);
			$this->common_func->publicView($data);
		}
	}
	function doPay()
	{
		$data['userInfo'] = $this->userInfo;
		$this->db->trans_begin();
		$tradecode = $this->common_func->createTradecode($_POST['tradecode']);
		if($tradecode != $data['userInfo']['tradecode'])
		{/*安全码出错*/
			$data['pay_result'] = array(
									'tips_img'=>'img/error.gif',
									'tips_text'=>'<span style="color: rgb(241, 132, 31);">支付订单失败：账户交易安全码输入错误</span><span><a href="'.site_url('member/order_center').'">查看订单列表</a>，对支付失败订单重新支付。账户交易安全码忘记？<a hreff="'.site_url('member/member_center/profile').'">重新设置安全码>></a></span>',
			);
		}
		else
		{
			if(($_POST['do_pay_num']*1 - $data['userInfo']['fund']*1) > 0)
			{/*可用余额小于支付余额*/
				if( ($data['userInfo']['fund']*1+$data['userInfo']['lock_fund']*1) >= $_POST['do_pay_num']*1 )
				{/*可用余额加冻结余额大于等于支付余额*/
					$data['pay_result'] = array(
									'tips_img'=>'img/alert.gif',
									'tips_text'=>'<span style="color: rgb(241, 132, 31);">支付订单失败：账户可用余额不够支付本次交易金额.</span><span>经查询，账户内有冻结金额，<a href="http://my.taobao.com/">登录我的淘宝</a>，确认收货充值订单来解冻账户<a href="'.site_url('member/member_center/finance').'">冻结资金</a>。</span>',
					);
				}
				else
				{
					$data['pay_result'] = array(
									'tips_img'=>'img/alert.gif',
									'tips_text'=>'<span style="color: rgb(241, 132, 31);">支付订单失败：账户可用余额不够支付本次交易金额.</span><span>请通过淘宝<a href="http://my.taobao.com/">充值</a>账户可用余额来支付本次交易订单。您可用随时支付本次支付失败的<a href="'.site_url('member/order_center').'">订单</a></span>',
					);
				}
			}
			else
			{
				$n = 0;
				foreach ($_POST['shop_type'] as $k=>$v)
				{
					if ($v == 0)
					{
						$n+= $this->Order_model->getOrderInfoNum($_POST['order_id'][$k]);
					}
				}
				$post_number_num = $this->Number_model->getNumberNum();
				if($n > $post_number_num)
				{
					$data['pay_result'] = array(
									'tips_img'=>'img/alert.gif',
									'tips_text'=>'<span style="color: rgb(241, 132, 31);">交易失败：没有足够库存来完成本次交易.</span><span>请联系或等待库存变化后跟进订单状态.<a href="'.site_url('member/order_center').'">查看订单>></a></span>',
					);
				}else{
					/*支付操作*/
					$shoping_re = $this->finance_func->shoping($_POST['do_pay_num']);
					$recordForFinanceData = array();
					/*具体购物操作开始*/
					foreach($_POST['shop_type'] as $k=>$v)
					{
						switch ($v)
						{
							/*根据购物类型进行不同的购物操作*/
							case 0://空包
								$financeRecordData = array('shop_type'=>$v,'pay_num'=>0,'order_num'=>0);
								$orderData = $this->Order_model->getOrderById($_POST['order_id'][$k]);
								foreach ($orderData[0]['info'] as $i=>$j)
								{
									$post_number = $this->Number_model->getNumber();
									$order_data['post_number'] = $post_number;
									$this->Order_model->setOrder($j['id'],$order_data);//更新运单号
									$this->Record_model->addRecord('shoping',array('shop_type'=>$v,'prince'=>$j['prince'],'order_info'=>$_POST['order_info'][$j['id']],'post_number'=>$post_number),$this->userInfo);//消费记录
									$financeRecordData['pay_num'] =+ $financeRecordData['pay_num']*1+$j['prince'];
									$financeRecordData['order_num'] ++;
								}
								$this->Record_model->addRecord('reFinance',$financeRecordData,$this->userInfo);//余额收支记录
								$this->Order_model->sendOrder($orderData[0]['id'],array('static'=>1));//发货
								break;
							case 1:
								$orderData = $this->Order_model->getOrderById($_POST['order_id'][$k]);
								foreach ($orderData[0]['info'] as $i=>$j)
								{
									$post_user_info = $this->finance_func->pass_finance($j);
									$this->Record_model->addRecord('reFinance',array('shop_type'=>$v,'pay_num'=>$j['prince'],'post_user'=>$post_user_info),$this->userInfo);//余额收支记录
									$this->Record_model->addRecord('passFinance',array('shop_type'=>$v,'pay_num'=>$j['prince'],'post_user'=>$post_user_info),$this->userInfo);//pass账户收支记录
								}
								$this->Order_model->sendOrder($orderData[0]['id'],array('static'=>2));//发货
								break;
							case 2:
								$financeRecordData = array('shop_type'=>$v,'pay_num'=>0,'order_num'=>0);
								$orderData = $this->Order_model->getOrderById($_POST['order_id'][$k]);
								foreach ($orderData[0]['info'] as $i=>$j)
								{
									$this->Record_model->addRecord('shoping',array('shop_type'=>$v,'prince'=>$j['prince'],'order_info'=>$_POST['order_info'][$j['id']],'post_number'=>$j['post_number']),$this->userInfo);//消费记录
									$financeRecordData['pay_num'] =+ $financeRecordData['pay_num']*1+$j['prince'];
									$financeRecordData['order_num'] ++;
								}
								$this->Record_model->addRecord('reFinance',$financeRecordData,$this->userInfo);//余额收支记录
								$this->Order_model->sendOrder($orderData[0]['id'],array('static'=>1));//发货
								break;
						}
					}
					/*具体购物操作结束*/
				}
			}
		}
		if ($this->db->trans_status() === FALSE)
		{
		    $this->db->trans_rollback();
		    $data['pay_result'] = array(
										'tips_img'=>'img/alert.gif',
										'tips_text'=>'<span style="color: rgb(241, 132, 31);">错误提示：系统故障！！！.</span><span>很抱歉的通知您，系统当前故障，该操作被意外终止，请稍后再进行该操作...</span>',
						);
		}
		else
		{
		    $this->db->trans_commit();
		    $data['pay_result'] = array(
									'tips_img'=>'img/ok.gif',
									'tips_text'=>'<span>支付成功：成功支付￥'.$_POST['do_pay_num'].'.</span><span>订单支付成功,请随时跟进订单状态.<a href="'.site_url('member/order_center').'">查看订单>></a></span>',
					);
		}
		$this->load->view('member/public/head',$data);
		$this->load->view('member/public/left');
		$this->load->view('member/public/pay_result');
		$this->load->view('member/public/foot');
	}
}